/**
 * 图表
 */

import * as Echarts from 'echarts';

export default (info = {}, dom) => {
  const { list = [] } = info || {};
  const xAxisData = [];
  const data = [];
  const chartData = {
    '2xx': {
      name: '2xx',
      data: [],
      type: 'bar',
      stack: 'total',
      label: {
        show: false,
        formatter: row => {
          return +row.value || '';
        },
      },
      itemStyle: {
        color: '#2E8B57',
      },
    },
    '3xx': {
      name: '3xx',
      data: [],
      type: 'bar',
      stack: 'total',
      label: {
        show: false,
        formatter: row => {
          return +row.value || '';
        },
      },
      itemStyle: {
        color: '#FFFACD',
      },
    },

    '4xx': {
      name: '4xx',
      data: [],
      type: 'bar',
      stack: 'total',
      label: {
        show: false,
        formatter: row => {
          return +row.value || '';
        },
      },
      itemStyle: {
        color: '#FFA500',
      },
    },
    '5xx': {
      name: '5xx',
      data: [],
      type: 'bar',
      stack: 'total',
      label: {
        show: false,
        formatter: row => {
          return +row.value || '';
        },
      },
      itemStyle: {
        color: '#EE6363',
      },
    },
  };
  list &&
    list.forEach((item, index) => {
      xAxisData.push(item.appName);
      Object.keys(chartData).forEach(k => {
        chartData[k].data.push(item[k]);
      });
    });
  const isShow = list && list.length;

  const echart = Echarts.init(dom);
  const option = {
    title: {
      top: 10,
      text: '应用TOP10',
      textStyle: {
        color: '#fff',
        fontFamily: 'webfont',
        fontSize: 15,
        fontWight: 'lighter',
      },
    },
    legend: {
      show: true,
      top: 10,
      right: '6%',
      textStyle: {
        color: '#fff',
      },
    },
    xAxis: {
      type: 'value',
      show: isShow,
      axisLabel: {
        color: '#cccccc',
      },
      splitLine: {
        show: false,
      },
    },
    yAxis: {
      type: 'category',
      data: xAxisData,
      show: isShow,
      axisLabel: {
        formatter: function(value, index) {
          //最长展示12个字符
          const str = String(value);
          return str.length > 12 ? str.slice(0, 12) + '...' : str;
        },
        color: '#fff',
      },
      splitLine: {
        show: false,
      },
    },
    grid: {
      top: '15%',
      left: '2%',
      right: '6%',
      bottom: '1%',
      containLabel: true,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    series: Object.values(chartData),
  };

  echart.setOption(option);
  return echart;
};
